package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.dsl.FXGL;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

import java.net.URL;
import java.util.Objects;
import java.util.Map;
import java.util.HashMap;

public class StorehouseScene extends FXGLScene {
    private StackPane sceneRoot;
    private javafx.scene.layout.GridPane gridPane;

    // 物品图片映射表（与HomeScene一致）
    private static final Map<String, String> itemImages = new HashMap<>();
    static {
        // 农作物
        itemImages.put("小麦", "/assets/textures/Fruit_Wheat.png");
        itemImages.put("番茄", "/assets/textures/Fruit_Tomato.png");
        itemImages.put("土豆", "/assets/textures/Fruit_Potato.png");
        itemImages.put("星果", "/assets/textures/Fruit_Starfruit.png");
        itemImages.put("胡萝卜", "/assets/textures/Fruit_Carrot.png");
        // 特殊农作物
        itemImages.put("南瓜", "/assets/textures/Fruit_Pumpkin.png");
        itemImages.put("霜瓜", "/assets/textures/Fruit_Powdermelon.png");
        itemImages.put("幽灵辣椒", "/assets/textures/Fruit_GhostPaper.png");
        itemImages.put("水龙果", "/assets/textures/Fruit_WaterDragon.png");
        itemImages.put("齐瓜", "/assets/textures/Fruit_Qi_Fruit.png");
        itemImages.put("世纪之花", "/assets/textures/Fruit_Plantera.png");
        // 种子
        itemImages.put("小麦种子", "/assets/textures/Seed_Wheat.png");
        itemImages.put("番茄种子", "/assets/textures/Seed_Tomato.png");
        itemImages.put("土豆种子", "/assets/textures/Seed_Potato.png");
        itemImages.put("星果种子", "/assets/textures/Seed_Starfruit.png");
        itemImages.put("胡萝卜种子", "/assets/textures/Seed_Carrot.png");
        // 特殊种子
        itemImages.put("南瓜种子", "/assets/textures/Seed_Pumpkin.png");
        itemImages.put("霜瓜种子", "/assets/textures/Seed_Powdermelon.png");
        itemImages.put("幽灵辣椒种子", "/assets/textures/Seed_GhostPaper.png");
        itemImages.put("水龙果种子", "/assets/textures/Seed_WaterDragon.png");
        itemImages.put("齐瓜种子", "/assets/textures/Seed_Qi_Bean.png");
        // 装备 - 剑
        itemImages.put("普通剑", "/assets/textures/Sword_Normal.png");
        itemImages.put("铁剑", "/assets/textures/Sword_Iron.png");
        itemImages.put("金剑", "/assets/textures/Sword_Golden.png");
        itemImages.put("钻石剑", "/assets/textures/Sword_Diamond.png");
        // 装备 - 头盔
        itemImages.put("铁头盔", "/assets/textures/Helmet_iron.png");
        itemImages.put("普通头盔", "/assets/textures/Helmet_normal.png");
        itemImages.put("金头盔", "/assets/textures/Helmet_golden.png");
        itemImages.put("钻石头盔", "/assets/textures/Helmet_diamond.png");
        // 装备 - 胸甲
        itemImages.put("铁胸甲", "/assets/textures/Chestplate_iron.png");
        itemImages.put("普通胸甲", "/assets/textures/Chestplate_normal.png");
        itemImages.put("金胸甲", "/assets/textures/Chestplate_golden.png");
        itemImages.put("钻石胸甲", "/assets/textures/Chestplate_diamond.png");
        // 装备 - 护腿
        itemImages.put("铁护腿", "/assets/textures/Legging_iron.png");
        itemImages.put("普通护腿", "/assets/textures/Legging_normal.png");
        itemImages.put("金护腿", "/assets/textures/Legging_golden.png");
        itemImages.put("钻石护腿", "/assets/textures/Legging_diamond.png");
        // 装备 - 靴子
        itemImages.put("铁靴子", "/assets/textures/Boot_iron.png");
        itemImages.put("普通靴子", "/assets/textures/Boot_normal.png");
        itemImages.put("金靴子", "/assets/textures/Boot_golden.png");
        itemImages.put("钻石靴子", "/assets/textures/Boot_diamond.png");
        // 钓鱼特殊物品
        itemImages.put("钓上来的头骨", "/assets/textures/Fishing_DeadPeople.png");
        itemImages.put("稀有破烂", "/assets/textures/Fishing_RareStuff.png");
        itemImages.put("石头", "/assets/textures/Fishing_Rock.png");
        itemImages.put("臭靴子", "/assets/textures/Fishing_Stinky_Boost.png");
        itemImages.put("木头", "/assets/textures/Fishing_Wood.png");
        // 第二阶段钓鱼物品
        itemImages.put("贝壳", "/assets/textures/Fishing_Clam.png");
        itemImages.put("珊瑚", "/assets/textures/Fishing_Coral.png");
        itemImages.put("死鱼", "/assets/textures/Fishing_DeadFish.png");

        // 新增材料类
        itemImages.put("史莱姆凝胶", "/assets/textures/Item_Slime.png");
        itemImages.put("昆虫肉", "/assets/textures/Item_Bug_Meat.png");
        // 新增装备类
        itemImages.put("幽灵剑", "/assets/textures/Sword_Ghost.png");
        itemImages.put("无头骑士剑", "/assets/textures/Sowrd_Pumpkin.png");
        itemImages.put("泰拉棱镜", "/assets/textures/Sword_Terraprisma.png");
        itemImages.put("喜庆之翼", "/assets/textures/Helmet_Festive_Wings.png");
        itemImages.put("幽灵靴子", "/assets/textures/Boots_Ghost.png");
        itemImages.put("幽灵护腿", "/assets/textures/Leggings_Ghost.png");
        itemImages.put("幽灵胸甲", "/assets/textures/Chestplate_Ghost.png");
        itemImages.put("幽灵头盔", "/assets/textures/Helmet_Ghost.png");
        itemImages.put("空间之主靴子", "/assets/textures/Boots_SpaceKing.png");
        itemImages.put("空间之主护腿", "/assets/textures/Legging_SpaceKing.png");
        itemImages.put("空间之主胸甲", "/assets/textures/Chestplate_SpaceKing.png");
        itemImages.put("空间之主头盔", "/assets/textures/Helmet_SpaceKing.png");
        itemImages.put("幼苗", "/assets/textures/Plantera_Seed.png");
    }

    public StorehouseScene() {
        // 在构造函数中立即隐藏player实体，避免时序问题
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        initUI();
    }

    protected void initUI() {
        // 初始化根容器
        sceneRoot = new StackPane();
        sceneRoot.setPrefSize(800, 600);
        sceneRoot.setStyle("-fx-background-color: transparent;");

        // 加载背景图片
        Image backgroundImg;
        try {
            backgroundImg = new Image(Objects.requireNonNull(
                    getClass().getResourceAsStream("/assets/textures/Shop.png")));
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            backgroundImg = null;
        }

        if (backgroundImg != null) {
            ImageView background = new ImageView(backgroundImg);
            background.setFitWidth(1000);
            background.setFitHeight(750);
            sceneRoot.getChildren().add(background);
        }

        // 主界面切换时不再stopAll，只在未播放时播放HomeMusic
        if (comgame.scenes.MusicManager.homeMusic == null)
            comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
        FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
        comgame.scenes.MusicManager.isHomeMusicPlaying = true;
        System.out.println("[HomeMusic] StorehouseScene loopMusic已调用");

        // 添加物品按钮区域
        gridPane = new javafx.scene.layout.GridPane();
        gridPane.setHgap(30);
        gridPane.setVgap(30);
        gridPane.setAlignment(Pos.CENTER);

        // 物品配置：图片路径、显示名称、是否装备、装备类型、实际物品名称
        Object[][] items = {
                {"/assets/textures/Seed_Carrot.png", "胡萝卜种子", false, "", "胡萝卜种子"},
                {"/assets/textures/Seed_Potato.png", "土豆种子", false, "", "土豆种子"},
                {"/assets/textures/Seed_Starfruit.png", "星果种子", false, "", "星果种子"},
                {"/assets/textures/Seed_Tomato.png", "番茄种子", false, "", "番茄种子"},
                {"/assets/textures/Seed_Wheat.png", "小麦种子", false, "", "小麦种子"},
                {"/assets/textures/Boot_normal.png", "靴子", true, "Boot", ""},
                {"/assets/textures/Helmet_normal.png", "头盔", true, "Helmet", ""},
                {"/assets/textures/Chestplate_normal.png", "胸甲", true, "Chestplate", ""},
                {"/assets/textures/Legging_normal.png", "护腿", true, "Legging", ""},
                {"/assets/textures/Sword_Normal.png", "剑", true, "Sword", ""},
                {"/assets/textures/Experience bottle.png", "经验瓶", false, "Experience", "经验瓶"}
        };

        double scale = 5;
        int col = 0, row = 0;
        for (int i = 0; i < items.length; i++) {
            Button btn = createSingleImageButton((String)items[i][0], (String)items[i][1], scale);
            String imagePath = (String)items[i][0];
            String displayName = (String)items[i][1];
            boolean isEquipment = (Boolean)items[i][2];
            String equipmentType = (String)items[i][3];
            String actualItemName = (String)items[i][4];

            if (isEquipment) {
                btn.setOnAction(e -> showEquipmentQualityDialog(equipmentType, displayName));
            } else if ("Experience".equals(equipmentType)) {
                btn.setOnAction(e -> showExperienceDialog());
            } else {
                btn.setOnAction(e -> showPurchaseDialog(imagePath, displayName, actualItemName));
            }
            gridPane.add(btn, col, row);
            col++;
            if (col == 3) {
                col = 0;
                row++;
            }
        }

        // 将GridPane添加到sceneRoot
        sceneRoot.getChildren().add(gridPane);
        // 添加返回按钮
        addBackButton();
        getContentRoot().getChildren().add(sceneRoot);
    }

    // 添加返回按钮的方法
    private void addBackButton() {
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");

        Button backBtn = createSingleImageButton(
                "/assets/textures/backbutton.png",
                "返回",
                0.1
        );

        StackPane.setAlignment(backBtn, Pos.TOP_LEFT);
        StackPane.setMargin(backBtn, new Insets(20, 0, 0, 20));

        backBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            System.out.println("返回主场景");
            comgame.scenes.DataSaveManager.saveAll();
            comgame.scenes.DataSaveManager.loadAll();
            FXGL.getGameScene().clearUINodes();
            GameScene gameScene = new GameScene();
            FXGL.getGameScene().addUINode(gameScene.getSceneRoot());
            // 确保player实体可见
            if (comgame.scenes.GameScene.playerEntity != null) {
                comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
            }
        });

        sceneRoot.getChildren().add(backBtn);

        // 添加WangDaMa按钮到左下角
        addWangDaMaButton();
    }

    // 添加WangDaMa按钮的方法
    private void addWangDaMaButton() {
        // 加载按钮音效
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("pop.wav");

        // 创建WangDaMa按钮
        Button wangDaMaBtn = createSingleImageButton(
                "/assets/textures/WangDaMa.png",
                "WangDaMa",
                15  // 缩放比例，可根据图片大小调整
        );

        // 设置按钮位置（左下角）
        StackPane.setAlignment(wangDaMaBtn, Pos.BOTTOM_LEFT);
        StackPane.setMargin(wangDaMaBtn, new Insets(0, 0, 50, 20));  // 左下角边距，往上移动30像素

        // 绑定点击事件
        wangDaMaBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);  // 播放点击音效
            System.out.println("WangDaMa按钮被点击！");

            // 显示个性化消息
            showWangDaMaDialog();
        });

        // 将按钮添加到场景
        sceneRoot.getChildren().add(wangDaMaBtn);
    }

    // 显示WangDaMa个性化对话框
    private void showWangDaMaDialog() {
        // 创建遮罩层
        StackPane overlay = new StackPane();
        overlay.setStyle("-fx-background-color: rgba(0,0,0,0.6);");
        overlay.setPrefSize(sceneRoot.getWidth(), sceneRoot.getHeight());

        // 弹窗主体
        StackPane dialog = new StackPane();
        dialog.setStyle("-fx-background-color: linear-gradient(to bottom right, #FFE4B5, #FFD700); -fx-background-radius: 20; -fx-border-radius: 20; -fx-border-color: #DAA520; -fx-border-width: 3;");
        dialog.setPadding(new Insets(40));
        dialog.setMaxWidth(400);
        dialog.setMaxHeight(350);  // 增加高度以容纳更多文字

        // WangDaMa图片
        Image wangDaMaImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/WangDaMa.png")));
        ImageView wangDaMaView = new ImageView(wangDaMaImg);
        wangDaMaView.setFitWidth(80);
        wangDaMaView.setFitHeight(80);

        // 个性化消息
        javafx.scene.control.Label messageLabel = new javafx.scene.control.Label("欢迎来到我的商店！\n我是王大妈，\n看看有什么想买的吗？\n或者你想卖点什么东西来换钱吗？");
        messageLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #8B4513; -fx-text-alignment: center;");
        messageLabel.setWrapText(true);
        messageLabel.setMaxWidth(320);  // 设置最大宽度确保文字能够正确换行

        // 关闭按钮
        Button closeBtn = new Button("谢谢！");
        closeBtn.setStyle("-fx-background-color: #DAA520; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius: 10; -fx-padding: 10 20;");
        closeBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));

        // 售卖按钮
        Button sellBtn = new Button("售卖物品");
        sellBtn.setStyle("-fx-background-color: #8B4513; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius: 10; -fx-padding: 10 20;");
        sellBtn.setOnAction(e -> {
            sceneRoot.getChildren().remove(overlay);
            showSellDialog();
        });

        // 按钮布局
        javafx.scene.layout.HBox buttonBox = new javafx.scene.layout.HBox(15, sellBtn, closeBtn);
        buttonBox.setAlignment(Pos.CENTER);

        // 布局
        javafx.scene.layout.VBox dialogContent = new javafx.scene.layout.VBox(20, wangDaMaView, messageLabel, buttonBox);
        dialogContent.setAlignment(Pos.CENTER);
        dialog.getChildren().add(dialogContent);
        overlay.getChildren().add(dialog);
        StackPane.setAlignment(dialog, Pos.CENTER);

        // 添加到场景
        sceneRoot.getChildren().add(overlay);
    }

    // 显示售卖对话框
    private void showSellDialog() {
        // 创建遮罩层
        StackPane overlay = new StackPane();
        overlay.setStyle("-fx-background-color: rgba(0,0,0,0.6);");
        overlay.setPrefSize(sceneRoot.getWidth(), sceneRoot.getHeight());

        // 弹窗主体
        StackPane dialog = new StackPane();
        dialog.setStyle("-fx-background-color: linear-gradient(to bottom right, #F5F5DC, #DEB887); -fx-background-radius: 20; -fx-border-radius: 20; -fx-border-color: #8B4513; -fx-border-width: 3;");
        dialog.setPadding(new Insets(30));
        dialog.setMaxWidth(600);  // 增加宽度以容纳更多内容
        dialog.setMaxHeight(500); // 增加高度以容纳滚轮

        // 标题
        javafx.scene.control.Label titleLabel = new javafx.scene.control.Label("售卖物品");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold; -fx-text-fill: #8B4513;");

        // 获取玩家物品（基于HomeScene中实际显示的物品）
        Map<String, Integer> playerItems = getPlayerActualItems();

        // 创建物品列表
        javafx.scene.layout.VBox itemsList = new javafx.scene.layout.VBox(10);
        itemsList.setAlignment(Pos.CENTER);
        itemsList.setPadding(new Insets(10)); // 添加内边距

        // 检查是否有可售卖的物品
        boolean hasItems = false;
        for (Map.Entry<String, Integer> entry : playerItems.entrySet()) {
            if (entry.getValue() > 0) {
                hasItems = true;
                break;
            }
        }

        if (!hasItems) {
            // 王大妈的个性化消息
            javafx.scene.control.Label noItemsLabel = new javafx.scene.control.Label("你个穷鬼啥也没有！");
            noItemsLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #8B0000;");
            itemsList.getChildren().add(noItemsLabel);
        } else {
            // 只显示玩家实际拥有的物品
            for (Map.Entry<String, Integer> entry : playerItems.entrySet()) {
                if (entry.getValue() > 0) {
                    javafx.scene.layout.HBox itemRow = createSellItemRow(entry.getKey(), entry.getValue());
                    itemsList.getChildren().add(itemRow);
                }
            }
        }

        // 创建滚轮容器
        javafx.scene.control.ScrollPane scrollPane = new javafx.scene.control.ScrollPane(itemsList);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(false);
        scrollPane.setVbarPolicy(javafx.scene.control.ScrollPane.ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(javafx.scene.control.ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setStyle("-fx-background: transparent; -fx-background-color: transparent;");
        scrollPane.setPrefViewportHeight(300); // 设置可视区域高度
        scrollPane.setMaxHeight(300); // 限制最大高度

        // 关闭按钮
        Button closeBtn = new Button("关闭");
        closeBtn.setStyle("-fx-background-color: #8B4513; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius: 10; -fx-padding: 10 20;");
        closeBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));

        // 布局
        javafx.scene.layout.VBox dialogContent = new javafx.scene.layout.VBox(20, titleLabel, scrollPane, closeBtn);
        dialogContent.setAlignment(Pos.CENTER);
        dialog.getChildren().add(dialogContent);
        overlay.getChildren().add(dialog);
        StackPane.setAlignment(dialog, Pos.CENTER);

        // 添加到场景
        sceneRoot.getChildren().add(overlay);
    }

    // 创建售卖物品行
    private javafx.scene.layout.HBox createSellItemRow(String itemName, int quantity) {
        javafx.scene.layout.HBox row = new javafx.scene.layout.HBox(15); // 增加间距
        row.setAlignment(Pos.CENTER);
        row.setPadding(new Insets(8, 5, 8, 5)); // 添加内边距
        row.setStyle("-fx-background-color: rgba(255,255,255,0.3); -fx-background-radius: 8;"); // 添加背景色

        // 物品图片
        String imagePath = getItemImagePath(itemName);
        ImageView itemImageView = null;
        try {
            Image img = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imagePath)));
            itemImageView = new ImageView(img);
            itemImageView.setFitWidth(40);
            itemImageView.setFitHeight(40);
        } catch (Exception e) {
            System.err.println("加载物品图片失败: " + imagePath + " - " + e.getMessage());
        }

        // 物品名称
        javafx.scene.control.Label nameLabel = new javafx.scene.control.Label(itemName + " x" + quantity);
        nameLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #333;");
        nameLabel.setMinWidth(140);
        nameLabel.setPrefWidth(140);

        // 价格显示
        int sellPrice = getSellPrice(itemName);
        javafx.scene.control.Label priceLabel = new javafx.scene.control.Label("售价: " + sellPrice + " 金币");
        priceLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666; -fx-font-weight: bold;");
        priceLabel.setMinWidth(100);
        priceLabel.setPrefWidth(100);

        // 数量选择器
        javafx.scene.layout.HBox quantityBox = new javafx.scene.layout.HBox(5);
        quantityBox.setAlignment(Pos.CENTER);
        quantityBox.setMinWidth(100);
        quantityBox.setPrefWidth(100);

        Button minusBtn = new Button("-");
        minusBtn.setStyle("-fx-background-color: #8B4513; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 12px; -fx-background-radius: 5; -fx-border-radius: 5; -fx-padding: 5 8;");
        minusBtn.setMinWidth(30);
        minusBtn.setPrefWidth(30);

        javafx.scene.control.Label quantityLabel = new javafx.scene.control.Label("1");
        quantityLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #333;");
        quantityLabel.setMinWidth(40);
        quantityLabel.setPrefWidth(40);
        quantityLabel.setAlignment(Pos.CENTER);

        Button plusBtn = new Button("+");
        plusBtn.setStyle("-fx-background-color: #8B4513; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 12px; -fx-background-radius: 5; -fx-border-radius: 5; -fx-padding: 5 8;");
        plusBtn.setMinWidth(30);
        plusBtn.setPrefWidth(30);

        // 数量控制逻辑
        int[] selectedQuantity = {1};
        Runnable decreaseAction = () -> {
            if (selectedQuantity[0] > 1) {
                selectedQuantity[0]--;
                quantityLabel.setText(String.valueOf(selectedQuantity[0]));
            }
        };
        Runnable increaseAction = () -> {
            if (selectedQuantity[0] < quantity) {
                selectedQuantity[0]++;
                quantityLabel.setText(String.valueOf(selectedQuantity[0]));
            }
        };
        setupLongPress(minusBtn, decreaseAction);
        setupLongPress(plusBtn, increaseAction);

        quantityBox.getChildren().addAll(minusBtn, quantityLabel, plusBtn);

        // 售卖按钮
        Button sellBtn = new Button("售卖");
        sellBtn.setStyle("-fx-background-color: #CD853F; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 14px; -fx-background-radius: 8; -fx-border-radius: 8; -fx-padding: 8 15;");
        sellBtn.setMinWidth(70);  // 增加宽度
        sellBtn.setPrefWidth(70);  // 增加宽度

        // 判断是否为"世纪之花"
        if ("世纪之花".equals(itemName)) {
            row.setOpacity(0.5); // 整行变灰

            // 移除价格显示
            priceLabel.setText("");
            priceLabel.setVisible(false);

            // 移除数量选择器
            quantityBox.setVisible(false);

            // 设置不可售卖按钮
            sellBtn.setText("不可售卖");
            sellBtn.setDisable(true);
            sellBtn.setMinWidth(110);
            sellBtn.setPrefWidth(110);
            sellBtn.setStyle("-fx-background-color: #888; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 8; -fx-border-radius: 8; -fx-padding: 8 15;");
            sellBtn.setTooltip(new javafx.scene.control.Tooltip("该物品不可售卖"));
            // 加锁图标
            try {
                Image lockImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/Box.png")));
                ImageView lockView = new ImageView(lockImg);
                lockView.setFitWidth(18);
                lockView.setFitHeight(18);
                javafx.scene.layout.StackPane imageStack = new javafx.scene.layout.StackPane();
                if (itemImageView != null) imageStack.getChildren().add(itemImageView);
                imageStack.getChildren().add(lockView);
                javafx.scene.layout.StackPane.setAlignment(lockView, Pos.BOTTOM_RIGHT);
                row.getChildren().add(0, imageStack);
            } catch (Exception e) {
                if (itemImageView != null) row.getChildren().add(0, itemImageView);
            }
            // 只添加必要的组件
            row.getChildren().addAll(nameLabel, sellBtn);
            return row;
        }

        // 为普通物品的售卖按钮添加点击事件
        sellBtn.setOnAction(e -> {
            // 获取当前选择的数量
            int sellQuantity = Integer.parseInt(quantityLabel.getText());
            int totalEarnings = sellPrice * sellQuantity;

            // 播放售卖音效
            FXGL.play("Money.wav");

            // 扣除物品数量
            ItemManager.getInstance().addItem(itemName, -sellQuantity);

            // 增加玩家金币
            if (GameScene.player != null) {
                GameScene.player.addMoney(totalEarnings);
            }

            // 显示售卖成功消息
            FXGL.showMessage("售卖成功！获得 " + totalEarnings + " 金币");

            // 刷新售卖对话框
            sceneRoot.getChildren().removeIf(node -> node instanceof StackPane &&
                    ((StackPane) node).getStyle().contains("rgba(0,0,0,0.6)"));
            showSellDialog();
        });

        // 将图片添加到最前面
        if (itemImageView != null) {
            row.getChildren().add(itemImageView);
        }
        row.getChildren().addAll(nameLabel, priceLabel, quantityBox, sellBtn);
        return row;
    }

    // 获取售卖价格
    private int getSellPrice(String itemName) {
        switch (itemName) {
            // 种子类
            case "胡萝卜种子": return 5;  // 10/2 = 5
            case "土豆种子": return 6;   // 12/2 = 6
            case "星果种子": return 25;  // 50/2 = 25
            case "番茄种子": return 8;   // 15/2 = 7.5，取整为8
            case "小麦种子": return 8;   // 15/2 = 7.5，取整为8
            case "南瓜种子": return 2;  // 南瓜种子2元
            case "霜瓜种子": return 10;  // 特殊种子售价10元
            case "幽灵辣椒种子": return 10; // 特殊种子售价10元
            case "水龙果种子": return 10; // 特殊种子售价10元
            case "齐瓜种子": return 10;  // 特殊种子售价10元

            // 收获的作物
            case "胡萝卜": return 15;  // 1个果实15元
            case "土豆": return 10;    // 1个果实10元
            case "小麦": return 21;    // 1个果实21元
            case "番茄": return 21;    // 1个果实21元
            case "星果": return 65;    // 1个果实65元
            case "南瓜": return 30;    // 1个果实30元
            case "霜瓜": return 40;    // 1个果实40元
            case "幽灵辣椒": return 85; // 1个果实85元
            case "水龙果": return 80;  // 1个果实80元
            case "齐瓜": return 100;   // 1个果实100元

            // 钓鱼获得的物品
            case "臭靴子": return 7;    // 臭鞋子7元
            case "钓上来的头骨": return 7; // 头骨7元
            case "稀有破烂": return 50;  // 稀有破烂50元
            case "石头": return 7;      // 石头7元
            case "木头": return 7;      // 木头7元
            case "贝壳": return 15;     //贝壳15元
            case "珊瑚": return 15;     //珊瑚15元
            case "死鱼": return 15;     //死鱼15元


            // 史莱姆凝胶
            case "史莱姆凝胶": return 2; // 史莱姆凝胶2元
            // 昆虫翅膀
            case "昆虫翅膀": return 25; // 昆虫翅膀5元
            case "昆虫肉" : return 5;

            // 装备类
            case "普通头盔": return 90;
            case "铁头盔": return 210;
            case "金头盔": return 360;
            case "钻石头盔": return 540;
            case "普通胸甲": return 180;
            case "铁胸甲": return 390;
            case "金胸甲": return 660;
            case "钻石胸甲": return 700;
            case "普通护腿": return 120;
            case "铁护腿": return 240;
            case "金护腿": return 420;
            case "钻石护腿": return 600;
            case "普通靴子": return 90;
            case "铁靴子": return 210;
            case "金靴子": return 360;
            case "钻石靴子": return 540;
            case "普通剑": return 120;
            case "铁剑": return 300;
            case "金剑": return 540;
            case "钻石剑": return 780;
            case "幽灵剑": return 800;
            case "幽灵头盔": return 800;
            case "幽灵胸甲": return 800;
            case "幽灵护腿": return 800;
            case "幽灵靴子": return 800;
            case "喜庆之翼": return 850;
            case "无头骑士剑": return 850;
            case "空间之主头盔": return 900;
            case "空间之主胸甲": return 900;
            case "空间之主护腿": return 900;
            case "空间之主靴子": return 900;
            case "泰拉棱镜": return 900;
            default: return 50;
        }
    }

    // 获取玩家实际拥有的物品（基于HomeScene中的逻辑）
    private Map<String, Integer> getPlayerActualItems() {
        Map<String, Integer> actualItems = new HashMap<>();
        Map<String, Integer> allItems = ItemManager.getInstance().getAllItems();

        // 获取玩家已装备装备名称
        java.util.HashSet<String> equippedNames = new java.util.HashSet<>();
        if (GameScene.player != null) {
            String[] equipTypes = {"sword", "helmet", "chestplate", "legging", "boot"};
            for (String type : equipTypes) {
                String eqName = GameScene.player.getEquippedItemName(type);
                if (eqName != null && !eqName.isEmpty()) {
                    equippedNames.add(eqName);
                }
            }
        }

        // 只包含数量大于0的物品，并排除工具类和已装备装备
        for (Map.Entry<String, Integer> entry : allItems.entrySet()) {
            String itemName = entry.getKey();
            int count = entry.getValue();

            // 排除工具类物品和已装备装备
            if (count > 0 && !isToolItem(itemName) && !equippedNames.contains(itemName)) {
                actualItems.put(itemName, count);
            }
        }

        return actualItems;
    }

    // 检查物品是否为工具类（不可售卖）
    private boolean isToolItem(String itemName) {
        switch (itemName) {
            case "水桶":
            case "锄头":
            case "心形":
                return true;
            default:
                return false;
        }
    }

    // 自动匹配物品图片路径
    private String getItemImagePath(String itemName) {
        // 优先查找映射表
        if (itemImages.containsKey(itemName)) {
            return itemImages.get(itemName);
        }
        // 你可以根据实际物品名和图片名的规律补充更多映射
        switch (itemName) {
            case "胡萝卜种子": return "/assets/textures/Seed_Carrot.png";
            case "土豆种子": return "/assets/textures/Seed_Potato.png";
            case "星果种子": return "/assets/textures/Seed_Starfruit.png";
            case "番茄种子": return "/assets/textures/Seed_Tomato.png";
            case "小麦种子": return "/assets/textures/Seed_Wheat.png";
            case "南瓜种子": return "/assets/textures/Seed_Pumpkin.png";
            case "霜瓜种子": return "/assets/textures/Seed_Powdermelon.png";
            case "幽灵辣椒种子": return "/assets/textures/Seed_GhostPaper.png";
            case "水龙果种子": return "/assets/textures/Seed_WaterDragon.png";
            case "齐瓜种子": return "/assets/textures/Seed_Qi_Bean.png";
            case "胡萝卜": return "/assets/textures/Fruit_Carrot.png";
            case "土豆": return "/assets/textures/Fruit_Potato.png";
            case "杨桃": return "/assets/textures/Fruit_Starfruit.png";
            case "番茄": return "/assets/textures/Fruit_Tomato.png";
            case "小麦": return "/assets/textures/Fruit_Wheat.png";
            case "南瓜": return "/assets/textures/Fruit_Pumpkin.png";
            case "霜瓜": return "/assets/textures/Fruit_Powdermelon.png";
            case "幽灵辣椒": return "/assets/textures/Fruit_GhostPaper.png";
            case "水龙果": return "/assets/textures/Fruit_WaterDragon.png";
            case "齐瓜": return "/assets/textures/Fruit_Qi_Fruit.png";
            case "史莱姆凝胶": return "/assets/textures/Item_Slime.png";
            case "昆虫肉": return "/assets/textures/Item_Bug_Meat.png";
            case "妙蛙种子": return "/assets/textures/Seed_Starfruit.png";
            case "幽灵剑": return "/assets/textures/Sword_Ghost.png";
            case "无头骑士剑": return "/assets/textures/Sowrd_Pumpkin.png";
            case "泰拉棱镜": return "/assets/textures/Sword_Terraprisma.png";
            case "喜庆之翼": return "/assets/textures/Helmet_Festive_Wings.png";
            case "幽灵靴子": return "/assets/textures/Boots_Ghost.png";
            case "幽灵护腿": return "/assets/textures/Leggings_Ghost.png";
            case "幽灵胸甲": return "/assets/textures/Chestplate_Ghost.png";
            case "幽灵头盔": return "/assets/textures/Helmet_Ghost.png";
            case "空间之主靴子": return "/assets/textures/Boot_normal.png";
            case "空间之主护腿": return "/assets/textures/Legging_normal.png";
            case "空间之主胸甲": return "/assets/textures/Chestplate_normal.png";
            case "空间之主头盔": return "/assets/textures/Helmet_normal.png";
            case "幼苗": return "/assets/textures/Plantera_Seed.png";
            default: return "/assets/textures/Box.png"; // 默认图标
        }
    }


    // 创建按钮的辅助方法
    private Button createSingleImageButton(String imagePath, String text, double scale) {
        // 修正路径：确保以斜杠开头
        if (!imagePath.startsWith("/")) {
            imagePath = "/" + imagePath;
        }

        // 通过URL加载（可抛出详细异常）
        URL imageUrl = getClass().getResource(imagePath);
        if (imageUrl == null) {
            throw new RuntimeException("资源未找到: " + imagePath);
        }

        // 计算目标尺寸
        Image rawImage = new Image(imageUrl.toExternalForm());
        double targetWidth = rawImage.getWidth() * scale;
        double targetHeight = rawImage.getHeight() * scale;

        // ✅ 高质量预缩放
        Image buttonImage = new Image(
                imageUrl.toExternalForm(),
                targetWidth, targetHeight, true, true, true
        );

        ImageView imageView = new ImageView(buttonImage);
        Button button = new Button();
        button.setGraphic(imageView);

        button.setPrefSize(imageView.getFitWidth(), imageView.getFitHeight());
        button.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");

        DropShadow shadow = new DropShadow();
        shadow.setColor(Color.WHITE);
        shadow.setRadius(10);

        button.setOnMouseEntered(e -> {
            button.setEffect(shadow);
            button.setOpacity(0.9);
        });

        button.setOnMouseExited(e -> {
            button.setEffect(null);
            button.setOpacity(1.0);
        });

        button.setOnMousePressed(e -> {
            button.setOpacity(0.8);          // 点击时更透明
            button.setScaleX(0.98);          // 轻微缩小
            button.setScaleY(0.98);
        });

        button.setOnMouseReleased(e -> {
            button.setOpacity(0.9);          // 恢复悬停状态
            button.setScaleX(1.0);           // 恢复大小
            button.setScaleY(1.0);
        });

        return button;
    }

    // 购买弹窗方法（种子类物品）
    private void showPurchaseDialog(String imagePath, String displayName, String actualItemName) {
        int price = getItemPrice(actualItemName);

        StackPane overlay = new StackPane();
        overlay.setStyle("-fx-background-color: rgba(0,0,0,0.4);");
        overlay.setPrefSize(sceneRoot.getWidth(), sceneRoot.getHeight());

        StackPane dialog = new StackPane();
        dialog.setStyle("-fx-background-color: white; -fx-background-radius: 15; -fx-border-radius: 15; -fx-border-color: #888; -fx-border-width: 2;");
        dialog.setPadding(new Insets(30));
        dialog.setMaxWidth(350);
        dialog.setMaxHeight(300);

        // 商品图片
        Image img = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imagePath)));
        ImageView imgView = new ImageView(img);
        imgView.setFitWidth(60);
        imgView.setFitHeight(60);

        // 商品名称
        javafx.scene.control.Label nameLabel = new javafx.scene.control.Label(displayName);
        nameLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333;");

        // 价格显示
        javafx.scene.control.Label priceLabel = new javafx.scene.control.Label("价格: " + price + " 金币");
        priceLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #666;");

        // 数量选择
        javafx.scene.control.Label qtyLabel = new javafx.scene.control.Label("1");
        qtyLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        int[] quantity = {1};
        Button minusBtn = new Button("-");
        Button plusBtn = new Button("+");
        // 替换原有setOnAction为长按
        Runnable decreaseAction = () -> {
            if (quantity[0] > 1) {
                quantity[0]--;
                qtyLabel.setText(String.valueOf(quantity[0]));
            }
        };
        Runnable increaseAction = () -> {
            quantity[0]++;
            qtyLabel.setText(String.valueOf(quantity[0]));
        };
        setupLongPress(minusBtn, decreaseAction);
        setupLongPress(plusBtn, increaseAction);
        javafx.scene.layout.HBox qtyBox = new javafx.scene.layout.HBox(10, minusBtn, qtyLabel, plusBtn);
        qtyBox.setAlignment(Pos.CENTER);

        // 确认/取消按钮
        Button confirmBtn = new Button("购买");
        Button cancelBtn = new Button("取消");
        javafx.scene.layout.HBox btnBox = new javafx.scene.layout.HBox(20, confirmBtn, cancelBtn);
        btnBox.setAlignment(Pos.CENTER);
        btnBox.setPadding(new Insets(15, 0, 0, 0));

        // 布局
        javafx.scene.layout.VBox dialogContent = new javafx.scene.layout.VBox(18, imgView, nameLabel, priceLabel, qtyBox, btnBox);
        dialogContent.setAlignment(Pos.CENTER);
        dialog.getChildren().add(dialogContent);
        overlay.getChildren().add(dialog);
        StackPane.setAlignment(dialog, Pos.CENTER);

        // 事件处理
        cancelBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));
        confirmBtn.setOnAction(e -> {
            FXGL.play("Money.wav");
            int totalCost = price * quantity[0];
            if (GameScene.player != null && GameScene.player.getMoney() >= totalCost) {
                // 扣除金币
                GameScene.player.addMoney(-totalCost);
                // 增加物品到仓库
                ItemManager.getInstance().addItem(actualItemName, quantity[0]);
                FXGL.showMessage("购买成功！");
                System.out.println("购买 " + actualItemName + " 数量: " + quantity[0] + " 花费: " + totalCost);
                // 测试购买系统
                testPurchaseSystem();
            } else {
                FXGL.showMessage("金币不足！需要 " + totalCost + " 金币");
            }
            sceneRoot.getChildren().remove(overlay);
        });

        sceneRoot.getChildren().add(overlay);
    }

    // 获取物品价格
    private int getItemPrice(String itemName) {
        switch (itemName) {
            case "胡萝卜种子": return 10;
            case "土豆种子": return 12;
            case "小麦种子": return 15;
            case "番茄种子": return 15;
            case "星果种子": return 50;
            default: return 100;
        }
    }

    // 装备品质选择弹窗
    private void showEquipmentQualityDialog(String equipmentType, String displayName) {
        StackPane overlay = new StackPane();
        overlay.setStyle("-fx-background-color: rgba(0,0,0,0.4);");
        overlay.setPrefSize(sceneRoot.getWidth(), sceneRoot.getHeight());

        StackPane dialog = new StackPane();
        dialog.setStyle("-fx-background-color: white; -fx-background-radius: 15; -fx-border-radius: 15; -fx-border-color: #888; -fx-border-width: 2;");
        dialog.setPadding(new Insets(30));
        dialog.setMaxWidth(400);
        dialog.setMaxHeight(380);  // 增加高度以容纳价格显示

        javafx.scene.control.Label titleLabel = new javafx.scene.control.Label(displayName + " 选择品质");
        titleLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333;");

        // 四种品质，顺序为普通、铁、金、钻石
        String[] qualities = {"普通", "铁", "金", "钻石"};
        String[] suffixes = {"Normal", "Iron", "Golden", "Diamond"};
        javafx.scene.layout.HBox qualityBox = new javafx.scene.layout.HBox(25);
        qualityBox.setAlignment(Pos.CENTER);

        for (int i = 0; i < qualities.length; i++) {
            String quality = qualities[i];
            String suffix = suffixes[i];
            String imgPath = "/assets/textures/" + equipmentType + "_" + suffix + ".png";

            try {
                Image img = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imgPath)));
                ImageView imgView = new ImageView(img);
                imgView.setFitWidth(60);
                imgView.setFitHeight(60);

                javafx.scene.control.Label qLabel = new javafx.scene.control.Label(quality);
                qLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

                // 添加价格显示
                int equipmentPrice = getEquipmentPrice(displayName, quality);
                javafx.scene.control.Label priceLabel = new javafx.scene.control.Label(equipmentPrice + " 金币");
                priceLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666; -fx-font-weight: bold;");

                Button buyBtn = new Button("购买");
                buyBtn.setOnAction(e -> {
                    FXGL.play("Money.wav");
                    String equipmentName = getEquipmentName(displayName, quality);

                    if (GameScene.player != null && GameScene.player.getMoney() >= equipmentPrice) {
                        GameScene.player.addMoney(-equipmentPrice);
                        ItemManager.getInstance().addItem(equipmentName, 1);
                        FXGL.showMessage("购买成功！");
                        System.out.println("购买 " + equipmentName + " 花费: " + equipmentPrice);
                        // 测试购买系统
                        testPurchaseSystem();
                    } else {
                        FXGL.showMessage("金币不足！需要 " + equipmentPrice + " 金币");
                    }
                    sceneRoot.getChildren().remove(overlay);
                });

                javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(8, imgView, qLabel, priceLabel, buyBtn);
                vbox.setAlignment(Pos.CENTER);
                qualityBox.getChildren().add(vbox);
            } catch (Exception e) {
                System.err.println("加载装备图片失败: " + imgPath + " - " + e.getMessage());
            }
        }

        Button cancelBtn = new Button("取消");
        cancelBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));
        javafx.scene.layout.HBox btnBox = new javafx.scene.layout.HBox(cancelBtn);
        btnBox.setAlignment(Pos.CENTER);
        btnBox.setPadding(new Insets(18, 0, 0, 0));

        javafx.scene.layout.VBox dialogContent = new javafx.scene.layout.VBox(18, titleLabel, qualityBox, btnBox);
        dialogContent.setAlignment(Pos.CENTER);
        dialog.getChildren().add(dialogContent);
        overlay.getChildren().add(dialog);
        StackPane.setAlignment(dialog, Pos.CENTER);
        sceneRoot.getChildren().add(overlay);
    }

    // 获取装备价格
    private int getEquipmentPrice(String baseName, String quality) {
        switch (baseName) {
            case "头盔":
                switch (quality) {
                    case "普通": return 150;
                    case "铁": return 350;
                    case "金": return 900;
                    case "钻石": return 1500;
                }
                break;
            case "胸甲":
                switch (quality) {
                    case "普通": return 300;
                    case "铁": return 650;
                    case "金": return 1500;
                    case "钻石": return 2700;
                }
                break;
            case "护腿":
                switch (quality) {
                    case "普通": return 200;
                    case "铁": return 400;
                    case "金": return 800;
                    case "钻石": return 1700;
                }
                break;
            case "靴子":
                switch (quality) {
                    case "普通": return 150;
                    case "铁": return 350;
                    case "金": return 700;
                    case "钻石": return 1700;
                }
                break;
            case "剑":
                switch (quality) {
                    case "普通": return 200;
                    case "铁": return 500;
                    case "金": return 1000;
                    case "钻石": return 2200;
                }
                break;
        }
        return 100;
    }

    // 获取装备完整名称
    private String getEquipmentName(String baseName, String quality) {
        return quality + baseName;
    }

    // 测试购买系统的方法
    private void testPurchaseSystem() {
        System.out.println("=== 购买系统测试 ===");
        System.out.println("当前玩家金币: " + (GameScene.player != null ? GameScene.player.getMoney() : "玩家未初始化"));
        System.out.println("ItemManager中的物品:");
        Map<String, Integer> allItems = ItemManager.getInstance().getAllItems();
        for (Map.Entry<String, Integer> entry : allItems.entrySet()) {
            if (entry.getValue() > 0) {
                System.out.println("  " + entry.getKey() + ": " + entry.getValue());
            }
        }
        System.out.println("==================");
    }

    // 通用长按自增/自减方法
    private void setupLongPress(Button button, Runnable action) {
        javafx.animation.Timeline timeline = new javafx.animation.Timeline(
            new javafx.animation.KeyFrame(javafx.util.Duration.millis(100), e -> action.run())
        );
        timeline.setCycleCount(javafx.animation.Animation.INDEFINITE);

        button.setOnMousePressed(e -> {
            action.run(); // 立即执行一次
            timeline.playFromStart();
        });
        button.setOnMouseReleased(e -> timeline.stop());
        button.setOnMouseExited(e -> timeline.stop());
    }

    public StackPane getSceneRoot() {
        return sceneRoot;
    }

    // 经验瓶对话框
    private void showExperienceDialog() {
        StackPane overlay = new StackPane();
        overlay.setStyle("-fx-background-color: rgba(0,0,0,0.4);");
        overlay.setPrefSize(sceneRoot.getWidth(), sceneRoot.getHeight());

        StackPane dialog = new StackPane();
        dialog.setStyle("-fx-background-color: white; -fx-background-radius: 15; -fx-border-radius: 15; -fx-border-color: #888; -fx-border-width: 2;");
        dialog.setPadding(new Insets(30));
        dialog.setMaxWidth(400);
        dialog.setMaxHeight(380);

        javafx.scene.control.Label titleLabel = new javafx.scene.control.Label("经验瓶");
        titleLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333;");

        // 经验瓶图片
        Image expImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/Experience bottle.png")));
        ImageView expView = new ImageView(expImg);
        expView.setFitWidth(60);
        expView.setFitHeight(60);

        // 检查玩家等级
        int playerLevel = 0;
        if (GameScene.player != null) {
            playerLevel = GameScene.player.getCombatLevel();
        }

        javafx.scene.control.Label messageLabel;
        javafx.scene.layout.HBox buttonBox = new javafx.scene.layout.HBox(15);
        buttonBox.setAlignment(Pos.CENTER);

        if (playerLevel >= 15) {
            // 15级后可以购买经验
            messageLabel = new javafx.scene.control.Label("可以用金币购买经验！\n每个经验瓶提供150经验值");
            messageLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #0066CC; -fx-text-alignment: center; -fx-padding: 0 0 0 0;");
            messageLabel.setWrapText(true);
            messageLabel.setMaxWidth(320);

            // 数量选择
            javafx.scene.control.Label qtyLabel = new javafx.scene.control.Label("1");
            qtyLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
            int[] quantity = {1};
            Button minusBtn = new Button("-");
            Button plusBtn = new Button("+");
            Runnable decreaseAction = () -> {
                if (quantity[0] > 1) {
                    quantity[0]--;
                    qtyLabel.setText(String.valueOf(quantity[0]));
                }
            };
            Runnable increaseAction = () -> {
                quantity[0]++;
                qtyLabel.setText(String.valueOf(quantity[0]));
            };
            setupLongPress(minusBtn, decreaseAction);
            setupLongPress(plusBtn, increaseAction);
            javafx.scene.layout.HBox qtyBox = new javafx.scene.layout.HBox(10, minusBtn, qtyLabel, plusBtn);
            qtyBox.setAlignment(Pos.CENTER);

            // 价格显示
            int pricePerBottle = 1000; // 每个经验瓶1000金币
            javafx.scene.control.Label priceLabel = new javafx.scene.control.Label("价格: " + pricePerBottle + " 金币/瓶");
            priceLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666; -fx-font-weight: bold; -fx-padding: 0 0 0 20;");

            // 购买按钮
            Button buyBtn = new Button("购买");
            buyBtn.setStyle("-fx-background-color: #4CAF50; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius: 10; -fx-padding: 10 20;");
                            buyBtn.setOnAction(e -> {
                    FXGL.play("Money.wav");
                    int totalCost = pricePerBottle * quantity[0];
                    if (GameScene.player != null && GameScene.player.getMoney() >= totalCost) {
                        GameScene.player.addMoney(-totalCost);
                        // 使用正确的方法增加经验
                        GameScene.player.addCombatExpAndLevelUp(150 * quantity[0]);
                        FXGL.showMessage("购买成功！获得 " + (150 * quantity[0]) + " 经验值");
                        System.out.println("购买经验瓶 x" + quantity[0] + " 花费: " + totalCost);
                        // 自动存档，确保经验数据被保存
                        comgame.scenes.DataSaveManager.saveAll();
                        // 强制刷新属性面板
                        comgame.scenes.GameScene.forceUpdatePlayerInfoPanel();
                    } else {
                        FXGL.showMessage("金币不足！需要 " + totalCost + " 金币");
                    }
                    sceneRoot.getChildren().remove(overlay);
                });

            Button cancelBtn = new Button("取消");
            cancelBtn.setStyle("-fx-background-color: #888; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius: 10; -fx-padding: 10 20;");
            cancelBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));

            buttonBox.getChildren().addAll(buyBtn, cancelBtn);

            // 布局
            javafx.scene.layout.VBox dialogContent = new javafx.scene.layout.VBox(18, titleLabel, expView, messageLabel, priceLabel, qtyBox, buttonBox);
            dialogContent.setAlignment(Pos.CENTER);
            dialog.getChildren().add(dialogContent);
        } else {
            // 15级前显示锁定提示
            messageLabel = new javafx.scene.control.Label("需要达到15级才能购买经验瓶！\n当前等级: " + playerLevel + "/15");
            messageLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #FF6B6B; -fx-text-alignment: center; -fx-padding: 0 0 0 0;");
            messageLabel.setWrapText(true);
            messageLabel.setMaxWidth(320);

            // 直接使用经验瓶图片，但调灰
            expView.setOpacity(0.3);

            Button closeBtn = new Button("知道了");
            closeBtn.setStyle("-fx-background-color: #888; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius: 10; -fx-padding: 10 20;");
            closeBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));

            buttonBox.getChildren().add(closeBtn);

            // 布局
            javafx.scene.layout.VBox dialogContent = new javafx.scene.layout.VBox(18, titleLabel, expView, messageLabel, buttonBox);
            dialogContent.setAlignment(Pos.CENTER);
            dialog.getChildren().add(dialogContent);
        }

        overlay.getChildren().add(dialog);
        StackPane.setAlignment(dialog, Pos.CENTER);
        sceneRoot.getChildren().add(overlay);
    }
}